<template>
  <div>
    <van-form
      @failed="onFailed"
      @submit="onSubmit"
      input-align="right"
      error-message-align="right"
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
    >
      <van-field
        :rules="[{ required: true, message: '请选择产奶日期' }]"
        @click="showDateSelect = true"
        label="产奶日期"
        input-align="right"
        required
        is-link
        readonly
        :value="contentObj.milkProductionDate"
      >
      </van-field>
      <van-popup v-model="showDateSelect" position="bottom">
        <van-datetime-picker type="date" @confirm="onConfirm" @cancel="showDateSelect = false" v-model="date" />
      </van-popup>
      <van-field
        label="早产奶量（kg）"
        v-model="contentObj.morningMilkProduction"
        label-width="40%"
        input-align="right"
        required
        type="number"
        placeholder="点击填写，保留1位小数"
        @keydown="valueChange"
      >
      </van-field>
      <van-field
        label="晚产奶量（kg）"
        input-align="right"
        label-width="40%"
        required
        type="number"
        placeholder="点击填写，保留1位小数"
        v-model="contentObj.nightMilkProduction"
        @keydown="valueChange"
      >
      </van-field>
      <van-field
        label="日产奶量（kg）"
        v-model="contentObj.dailyMilkProduction"
        label-width="40%"
        input-align="right"
        type="number"
        required
        readonly
      />
      <van-field
        label="养只数量（只）"
        @click="sheepGo"
        readonly
        is-link
        :value="contentObj.quantity"
        label-width="40%"
        input-align="right"
        required
      >
      </van-field>
      <van-button
        block
        color="#37B5B5"
        type="info"
        style="width: 85%; margin: auto; margin-top: 50px"
        size="large"
        native-type="submit"
        :loading="loading"
        loading-text="提交中..."
        >保存</van-button
      >
      <div style="height: 20px"></div>
    </van-form>
  </div>
</template>
<script>
import { Form, Field, Dialog, Toast, DatetimePicker, Picker, Button, Popup } from 'vant'

import TitlePanel from '@/components/titlePanel'
import { getValue, clearValue, setValue } from '@/utils/auth'
import { postHandle, getHandle } from '@/api'
import dayjs from 'dayjs'
export default {
  components: {
    TitlePanel,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Toast.name]: Toast,
    [Dialog.Component.name]: Dialog.Component,
    [Button.name]: Button,
    [Popup.name]: Popup
  },
  data() {
    return {
      date: new Date(),
      contentObj: {
        subjectInfoId: getValue('subjectInfoId'),
        tenantCode: getValue('tenantCode'),
        nightMilkProduction: null,
        morningMilkProduction: null,
        dailyMilkProduction: null,
        quantity: null,
        individualInfoIds: null
      },
      loading: false,
      milkRecordId: getValue('milkRecordId'),
      sellDate: '',
      showDateSelect: false
    }
  },
  watch: {
    contentObj: {
      handler() {
        this.contentObj.dailyMilkProduction =
          Number(this.contentObj.nightMilkProduction) + Number(this.contentObj.morningMilkProduction)
      },
      deep: true
    }
  },
  created() {
    this.$bridge.register('refresh', data => {
    if (getValue('sheep-object')) {
      let sheepObject = JSON.parse(getValue('sheep-object'))
      this.contentObj = sheepObject
    } else {
      this.initialize()
    }
    if (getValue('earTag2')) {
      let data = JSON.parse(getValue('earTag2'))
      data.forEach((item, index) => {
        this.contentObj.quantity = index + 1
        this.contentObj.individualInfoIds = data
      })
    }
    })
  },
  methods: {
    goCompile() {
      this.$bridge.call('milkEdit')
    },
    initialize() {
      getHandle(`/agri/api/yzbzh/milkProductionRecord/queryDetail/${this.milkRecordId}`).then(res => {
        this.contentObj = res.data
        this.contentObj.milkProductionDate = dayjs(this.contentObj.milkProductionDate).format('YYYY-MM-DD')
      })
    },
    onConfirm(time) {
      this.contentObj.milkProductionDate = dayjs(time).format('YYYY-MM-DD')
      this.showDateSelect = false
    },
    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message)
    },
    onSubmit(value) {
      this.loading = true
      this.onSave()
    },
    onSave() {
      postHandle(`/agri/api/yzbzh/milkProductionRecord/update/${this.milkRecordId}`, this.contentObj)
        .then(res => {
          this.$toast.success(res.msg)
          this.loading = false
          clearValue('milkRecordId')
          clearValue('earTag2')
          clearValue('sheep-object')
          clearValue('fzmSex')
          this.$bridge.call('base.closePage')
        })
        .catch(() => {
          this.$toast(res.msg)
          this.loading = false
        })
    },
    valueChange(e) {
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,0})/)[0] || null
    },
    sheepGo() {
      // setValue('earTag3Type', 'EXPERT_TYPE_EWE')
      setValue('fzmSex', '母')
      setValue('earTag2', JSON.stringify(this.contentObj.individualInfoIds))
      setValue('sheep-object', JSON.stringify(this.contentObj))
      this.$bridge.call('addCheckEarTag2')
    }
  }
}
</script>
<style lang="scss" scoped>
.flex-between {
  line-height: 2em;
}
::v-deep .van-cell::after {
  border-color: #eeeeee !important;
}
::v-deep .van-cell:last-child {
  border: none !important;
}
.footerImg {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #37b5b5;
  > img {
    width: 22px;
    height: 22px;
  }
}
.shop .bottom {
  position: fixed;
  bottom: 0;
  height: 68px;
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  padding: 8px 10px 8px 14px;
  box-shadow: 0px -2px 5px 0px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.addbtn {
  width: 50px;
  height: 24px;
  font-size: 13px;
  padding: 0;
  margin-top: 2px;
}
.border {
  height: 68px;
  width: 1px;
  background: #eeeeee;
}
</style>
